package com.yugao.fintech.draper.sequence.segment.mysql;

import com.yugao.fintech.draper.sequence.exception.SequenceException;
import com.yugao.fintech.draper.sequence.segment.mysql.service.JdbcSegmentService;
import com.yugao.fintech.draper.sequence.segment.SeqSegment;
import com.yugao.fintech.draper.sequence.segment.SeqSegmentConfig;
import com.yugao.fintech.draper.sequence.segment.SeqSegmentManager;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * mysql号段管理器
 */
@Slf4j
@Component
@RequiredArgsConstructor
@ConditionalOnProperty(prefix = "draper.sequence", value = "type", havingValue = "mysql", matchIfMissing = true)
public class JdbcSeqSegmentManager implements SeqSegmentManager {

    private final JdbcSegmentService jdbcSegmentService;

    private static Map<String, SeqSegment> seqRangeMap = new ConcurrentHashMap<>(8);

    /**
     * 获取指定号段名的下一个号段
     *
     * @param name             号段名
     * @param seqSegmentConfig 序列号号段配置
     * @return 返回号段
     * @throws SequenceException 序列号异常
     */
    @Override
    public SeqSegment nextSegment(String name, SeqSegmentConfig seqSegmentConfig) throws SequenceException {
        SeqSegment seqSegment = seqRangeMap.get(name);
        if (Objects.isNull(seqSegment)) {
            // 不存在就set，存在就忽略
            jdbcSegmentService.setIfAbsentRange(name, seqSegmentConfig.getRangeStart());
        }
        Integer rangeStep = seqSegmentConfig.getRangeStep();
        Long max = jdbcSegmentService.incrementRange(name, rangeStep);
        Long min = max - rangeStep;
        seqSegment = new SeqSegment(min, max, seqSegmentConfig.getStep());
        seqRangeMap.put(name, seqSegment);
        return seqSegment;
    }
}
